<template>
  <div id="DeviceTree">
    <div class="page-header">
      <el-radio-group size="mini" @change="handleRadioChange" v-model="form.deviceType">
          <el-radio-button   label="CAMERA">监控</el-radio-button>
          <el-radio-button v-if="$route.query.type === 'PB'"  label="PC">电脑</el-radio-button>
        </el-radio-group>
      <div class="page-title" > 
        <span>设备列表</span>
        <el-input
            style="width: 180px;margin-left: auto;"
            size="mini"
            placeholder="关键字"
            prefix-icon="el-icon-search"
            v-model="searchSrt"
            clearable
          ></el-input></div>
      <div class="page-header-btn">
        <div style="display: inline">
         
        </div>
      </div>
    </div>
    <div>
      <el-tree :data="treeData" default-expand-all ref="tree_dom" v-loading="loading"
       :props="props"  :filter-node-method="filterNode"    @node-click="nodeClickHandler"></el-tree>
    </div>
  </div>
</template>

<script>
// import VueEasyTree from "@wchbrad/vue-easy-tree";
// import regionEdit from "./../dialog/regionEdit";
// import gbDeviceSelect from "./../dialog/GbDeviceSelect";
import { deviceLevelList } from '@/api/pageVideoWitness'
// import { EventBus } from "../service/eventBus";
export default {
  name: "DeviceTree",
  components: {
    // VueEasyTree,
  },
  watch:{
    searchSrt(val) {
        this.$refs.tree_dom.filter(val);
      }
  },
  data() {
    return {
      loading:false,
      currProjectData:{},
      treeRadio:'监控',
      props: {
        label: "roomName",
        children:'deviceList'
      },
      showCode: false,
      searchSrt: "",
      chooseId: "",
      treeData: [],
      form:{
        taskType:'PB',
        status:'JZZ', // JZZ见证中、YWC已完成
        deviceType:'CAMERA' //CAMERA、PC
      }
    };
  },
  props: ["edit", "clickEvent", "chooseIdChange", "onChannelChange", "showHeader"],
  created(){
    const { type,taskstatus,bdid,taskid } = this.$route.query;
    this.$set(this.form,'taskType',type)
    // this.$set(this.form,'status',taskstatus)

  },
  mounted() {
    // EventBus.$on("currProjectData",(data)=>{
    //   // console.log("currProjectData,拿到值",data);
    //   this.currProjectData = data
    //   this.deviceLevelList()
    // })
    this.deviceLevelList()
  },
  beforeDestroy(){
    // EventBus.$off("currProjectData")
  },
  methods: {
    handleRadioChange(val){
      // this.$set(this.form,'deviceType',val)
      // 切换接口
      this.deviceLevelList()
      
    },
    nodeClickHandler: function (data, node, tree) {
      if(!this.clickEvent) return 
       this.clickEvent(data,this.form.deviceType);
    },
    // 搜索
    filterNode(value, data) {
        if (!value) return true;
        return data.roomName.indexOf(value) !== -1;
      },

    search() {

    },
    deviceLevelList(){
      console.log('form',this.form);
      this.loading = true
      deviceLevelList(this.form).then(res=>{
        console.log('res',res);
       if(res.success){
       res.data.forEach(e => {
          e.deviceList.forEach(x=>{
             x.roomName =x.deviceName
             x.roomId =x.deviceId
             x.deviceList = null
          })
          
        });
        this.loading = false
        this.treeData = res.data
       }
      })
    },
    // loadNode: function (node, resolve) {
    //   if (node.level === 0) {
    //     resolve([
    //       {
    //         treeId: "",
    //         deviceId: "",
    //         name: "根资源组",
    //         isLeaf: false,
    //         type: 0
    //       }
    //     ]);
    //   } else if (node.data.deviceId.length <= 8) {
    //     if (node.data.leaf) {
    //       resolve([]);
    //       return;
    //     }
    //     resolve([]);
    //     // this.$axios({
    //     //   method: "get",
    //     //   url: `/api/region/tree/list`,
    //     //   params: {
    //     //     query: this.searchSrt,
    //     //     parent: node.data.id
    //     //   }
    //     // })
    //     //   .then((res) => {
    //     //     if (res.data.code === 0) {
    //     //       resolve(res.data.data);
    //     //     }
    //     //   })
    //     //   .catch(function (error) {
    //     //     console.log(error);
    //     //   });
    //   } else {
    //     resolve([]);
    //   }
    // },
    reset: function () {
      this.$forceUpdate();
    },
    contextmenuEventHandler: function (event, data, node, element) {
      if (!this.edit) {
        return;
      }
      console.log(node.level);
      if (node.data.type === 1) {
        data.parentId = node.parent.data.id;
        this.$contextmenu({
          items: [
            {
              label: "移除通道",
              icon: "el-icon-delete",
              disabled: false,
              onClick: () => {
                console.log(data);
                this.$axios({
                  method: "post",
                  url: `/api/common/channel/region/delete`,
                  data: {
                    channelIds: [data.id]
                  }
                })
                  .then((res) => {
                    console.log("移除成功");
                    if (this.onChannelChange) {
                      this.onChannelChange();
                    }
                    node.parent.loaded = false;
                    node.parent.expand();
                  })
                  .catch(function (error) {
                    console.log(error);
                  });
              }
            }
          ],
          event, // 鼠标事件信息
          customClass: "custom-class", // 自定义菜单 class
          zIndex: 3000 // 菜单样式 z-index
        });
      } else if (node.data.type === 0) {
        this.$contextmenu({
          items: [
            {
              label: "刷新节点",
              icon: "el-icon-refresh",
              disabled: false,
              onClick: () => {
                this.refreshNode(node);
              }
            },
            {
              label: "新建节点",
              icon: "el-icon-plus",
              disabled: false,
              onClick: () => {
                this.addRegion(data.id, node);
              }
            },
            {
              label: "编辑节点",
              icon: "el-icon-edit",
              disabled: node.level === 1,
              onClick: () => {
                this.editCatalog(data, node);
              }
            },
            {
              label: "删除节点",
              icon: "el-icon-delete",
              disabled: node.level === 1,
              divided: true,
              onClick: () => {
                this.$confirm("确定删除?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                })
                  .then(() => {
                    this.removeRegion(data.id, node);
                  })
                  .catch(() => {});
              }
            },
            {
              label: "添加设备",
              icon: "el-icon-plus",
              disabled: node.level === 1,
              onClick: () => {
                this.addChannelFormDevice(data.id, node);
              }
            },
            {
              label: "移除设备",
              icon: "el-icon-delete",
              disabled: node.level === 1,
              onClick: () => {
                this.removeChannelFormDevice(data.id, node);
              }
            }
            // {
            //   label: "导出",
            //   icon: "el-icon-download",
            //   disabled: false,
            //   children: [
            //     {
            //       label: "导出到文件",
            //       onClick: () => {
            //
            //       },
            //     },
            //     {
            //       label: "导出到其他平台",
            //       onClick: () => {
            //
            //       },
            //     }
            //   ]
            // },
          ],
          event, // 鼠标事件信息
          customClass: "custom-class", // 自定义菜单 class
          zIndex: 3000 // 菜单样式 z-index
        });
      }

      return false;
    },
    removeRegion: function (id, node) {
      this.$axios({
        method: "delete",
        url: `/api/region/delete`,
        params: {
          id: node.data.id
        }
      })
        .then((res) => {
          if (res.data.code === 0) {
            console.log("移除成功");
            node.parent.loaded = false;
            node.parent.expand();
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    addChannelFormDevice: function (id, node) {
      this.$refs.gbDeviceSelect.openDialog((rows) => {
        let deviceIds = [];
        for (let i = 0; i < rows.length; i++) {
          deviceIds.push(rows[i].id);
        }
        this.$axios({
          method: "post",
          url: `/api/common/channel/region/device/add`,
          data: {
            civilCode: node.data.deviceId,
            deviceIds: deviceIds
          }
        })
          .then((res) => {
            if (res.data.code === 0) {
              this.$message.success({
                showClose: true,
                message: "保存成功"
              });
              if (this.onChannelChange) {
                this.onChannelChange();
              }
              node.loaded = false;
              node.expand();
            } else {
              this.$message.error({
                showClose: true,
                message: res.data.msg
              });
            }
            this.loading = false;
          })
          .catch((error) => {
            this.$message.error({
              showClose: true,
              message: error
            });
            this.loading = false;
          });
      });
    },
    removeChannelFormDevice: function (id, node) {
      this.$refs.gbDeviceSelect.openDialog((rows) => {
        let deviceIds = [];
        for (let i = 0; i < rows.length; i++) {
          deviceIds.push(rows[i].id);
        }
        this.$axios({
          method: "post",
          url: `/api/common/channel/region/device/delete`,
          data: {
            deviceIds: deviceIds
          }
        })
          .then((res) => {
            if (res.data.code === 0) {
              this.$message.success({
                showClose: true,
                message: "保存成功"
              });
              if (this.onChannelChange) {
                this.onChannelChange();
              }
              node.loaded = false;
              node.expand();
            } else {
              this.$message.error({
                showClose: true,
                message: res.data.msg
              });
            }
            this.loading = false;
          })
          .catch((error) => {
            this.$message.error({
              showClose: true,
              message: error
            });
            this.loading = false;
          });
      });
    },
    refreshNode: function (node) {
      node.loaded = false;
      node.expand();
    },
    refresh: function (id) {
      // 查询node
      let node = this.$refs.veTree.getNode(id);
      if (node) {
        node.loaded = false;
        node.expand();
      }
    },
    addRegion: function (id, node) {
      console.log(node);

      this.$refs.regionEdit.openDialog(
        (form) => {
          node.loaded = false;
          node.expand();
        },
        {
          deviceId: "",
          name: "",
          parentId: node.data.id,
          parentDeviceId: node.data.deviceId
        }
      );
    },
    editCatalog: function (data, node) {
      // 打开添加弹窗
      this.$refs.regionEdit.openDialog((form) => {
        node.loaded = false;
        node.expand();
      }, node.data);
    },

  },
  destroyed() {

  }
};
</script>

<style lang="scss" scoped>


#DeviceTree{
  width: 100%;
}
.page-title{
  display: flex;
  padding: 4px;
  font-size: 16px;
  height: 30px;
  line-height: 30px;
  background-color: rgba(170, 170, 170, 0.95);
  color: #333;
  // border: 1px solid #e5e5e5;
}

</style>
